/**
 * 文件名：AttachmentController.java
 *
 * 版本信息：v1.0
 * 日期：2013-6-20
 * Copyright  Corporation 2013
 * 版权所有
 *
 */

package com.foreveross.bsl.mam.model.web;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.foreveross.bsl.common.utils.bean.FileUtils;
import com.foreveross.bsl.common.utils.context.ContextThead;
import com.foreveross.bsl.file.storage.FileStorage;
import com.foreveross.bsl.file.storage.FileStorageFactory;
import com.foreveross.bsl.mam.model.application.AttachmentApplication;
import com.foreveross.bsl.mam.model.application.vo.AttachmentVO;
import com.taobao.common.tfs.packet.FileInfo;

/**
 * 此类描述的是：文件模块控制器
 *
 * @author: panhm@foreveross.com
 * @version: 2013-6-20 下午2:51:04
 */
@Controller
@RequestMapping("/mam/attachment")
public class AttachmentController {

	private Log log = LogFactory.getLog(AttachmentController.class);

	@Inject
	private AttachmentApplication attachmentApplication;

	/**
	 * 此方法描述的是：应用个性化设置logo上传
	 *
	 * @author: panhm@foreveross.com
	 * @version: 2013-7-26 下午12:44:23
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.POST, value = "/appImageUpload")
	public ResponseEntity<Map<String, Object>> appImageUpload(
			HttpServletRequest request,
			@RequestParam("picArray") String[] picArray,
			HttpServletResponse response) {

		Map<String, Object> result = new HashMap<String, Object>();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 获得文
		MultipartFile file = multipartRequest.getFile("file");
		// List<String> resultList = new ArrayList<String>();
		ResponseEntity<Map<String, Object>> res = null;
		try {
			if (file != null) {
				List<String> list = new ArrayList<String>();
				for (int i = 0; i < picArray.length; i++) {
					String sizeStr = picArray[i];
					String valus[] = sizeStr.split("\\*");

					// 保存上传图片信息
					AttachmentVO entity = new AttachmentVO();
					Date date = new Date();
					entity.setAvailable(1);
					entity.setContentType(file.getContentType());
					entity.setCreatedAt(date);
					entity.setModifiedAt(date);
					entity.setUploadFilename(file.getOriginalFilename());
					entity.setSize(file.getSize());

					// 生成指定格式大小的图片数据
					ByteArrayOutputStream out = new ByteArrayOutputStream();
					Thumbnails
							.of(file.getInputStream())
							.size(Integer.parseInt(valus[0]),
									Integer.parseInt(valus[1]))
							.keepAspectRatio(false).toOutputStream(out);
					// 将图片保存到云服务
					FileStorageFactory f = FileStorageFactory.getInstance();
					FileStorage fs = f.getFileStorage();

					String id = fs.saveFile(out.toByteArray(), null, null);
					entity.setId(id);
					entity.setLocalFilename(id);
					AttachmentVO resultVo = attachmentApplication
							.saveEntity(entity);
					list.add(resultVo.getId());
				}
				result.put("data", list);
				res = new ResponseEntity<Map<String, Object>>(result,
						HttpStatus.OK);
			} else {
				res = new ResponseEntity<Map<String, Object>>(
						HttpStatus.BAD_REQUEST);
				log.info("[appImageUpload]" + HttpStatus.BAD_REQUEST);
			}
		} catch (Exception e) {
			log.error("[appImageUpload]", e);
			res = new ResponseEntity<Map<String, Object>>(
					HttpStatus.INTERNAL_SERVER_ERROR);
		}

		return res;
	}

	/**
	 * 此方法描述的是：文件上传处理
	 *
	 * @author: panhm@foreveross.com
	 * @version: 2013-7-26 下午12:46:37
	 */

	@ResponseBody
	@RequestMapping(method = RequestMethod.POST, value = "/upload")
	public Map<String, String> upload(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, String> result = new HashMap<String, String>();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 获得文件：
		MultipartFile file = multipartRequest.getFile("file");

		try {
			if (file != null) {
				// 保存上传文件信息
				AttachmentVO entity = new AttachmentVO();
				Date date = new Date();
				entity.setAvailable(1);
				entity.setContentType(file.getContentType());
				entity.setCreatedAt(date);
				entity.setModifiedAt(date);
				entity.setUploadFilename(file.getOriginalFilename());
				entity.setSize(file.getSize());
				entity.setUserName(ContextThead.getThreadVar());
				// 将图片保存到云服务
				FileStorageFactory f = FileStorageFactory.getInstance();
				FileStorage fs = f.getFileStorage();
				String id = fs.saveFile(file.getBytes(), null, null);
				entity.setId(id);
				entity.setLocalFilename(id);
				AttachmentVO resultVo = attachmentApplication
						.saveEntity(entity);
				result.put("result", "success");
				result.put("id", resultVo.getId());
			} else {
				result.put("result", "error");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("[upload]", e);
			result.put("result", "error");
		}
		return result;
	}

	/**
	 * 此方法描述的是：文件下载接口
	 *
	 * @author: panhm@foreveross.com
	 * @version: 2013-7-26 下午12:47:29
	 */

	@RequestMapping(method = RequestMethod.GET, value = "/download/{id:.+}")
	public void download(@PathVariable String id, HttpServletResponse response,
			HttpServletRequest request) {
		try {
			log.info("[attachment]" + id);
			AttachmentVO entity = attachmentApplication.getEntity(id);
			if (entity != null && entity.getId() != null) {
				// 读取云服务文件
				FileStorageFactory f = FileStorageFactory.getInstance();
				FileStorage fs = f.getFileStorage();
				FileInfo fileInfo = fs.statFile(entity.getLocalFilename(), null);
				log.info("[data]" + fileInfo.getLength());
				response.setStatus(200);
				response.setHeader(
						"Content-Disposition",
						String.format("attachment;   filename=%s",
								entity.getUploadFilename()));
				response.setContentType(entity.getContentType());
				response.setHeader("Content-Length", fileInfo.getLength() + "");
				OutputStream outputStream = response.getOutputStream();
				fs.fetchFile(entity.getLocalFilename(), null, outputStream);
				outputStream.flush();
				outputStream.close();
			} else {
				log.info("[response]" + 400);
				response.setStatus(400);
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO Auto-generated catch block
			log.error("[download]", e);
			response.setStatus(500);
		}
	}

	/**
	 * 读取模块包的配置文件信息
	 *
	 * @param id
	 * @param response
	 * @param request
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.GET, value = "/readfile/{id:.+}")
	public Map<String, Object> readfile(@PathVariable String id,
			HttpServletResponse response, HttpServletRequest request) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("result", "error"); // 默认是返回失败
			// 获取模块包信息
			AttachmentVO entity = attachmentApplication.getEntity(id);

			// 读取云服务模块包，存放到本地指定目录
			FileStorageFactory f = FileStorageFactory.getInstance();
			FileStorage fs = f.getFileStorage();
			String localFileName = entity.getLocalFilename();
			fs.fetchFile(localFileName, null, FileUtils.dirPath
					+ File.separator + localFileName);
			File file = new File(FileUtils.dirPath + File.separator
					+ localFileName);
			//  读取模块zip包里面的配置文件信息
			String stringJson =null;
			try {stringJson=FileUtils.readZipConfig(file, "package.json"); // hyw add 20140623
			} catch (Exception e) {}

		  if(stringJson == null || "".equals(stringJson)) {
    			stringJson = FileUtils.readZipConfig(file, "CubeModule.json");
			}
	    if (stringJson != null) {
			JSONObject json = new JSONObject(stringJson.trim());
			log.info("CubeModule.json:" + json.toString());
			jsonMap.put("identifier", json.getString("identifier"));
			jsonMap.put("name", json.getString("name"));
			jsonMap.put("releaseNote", json.getString("releaseNote"));
			jsonMap.put("version", json.getString("version"));
			jsonMap.put("build", json.getString("build"));
			if (!json.isNull("dependencies")) {
				jsonMap.put("dependsOn", json.getString("dependencies"));
			}
			if (!json.isNull("hidden")) {
				jsonMap.put("hidden", json.getString("hidden"));
			}
			if (!json.isNull("icon")) {
				String icon = json.getString("icon");
				byte[] iconBytes = FileUtils.readPngFile(file, icon);
				// 读取logo图片字节,然后生成图片，保存到文件存储表
				entity = new AttachmentVO();
				Date date = new Date();
				entity.setAvailable(1);
				entity.setContentType("images/png");
				entity.setCreatedAt(date);
				entity.setModifiedAt(date);
				entity.setUploadFilename(icon);
				entity.setSize(iconBytes.length);
				String fileid = fs.saveFile(iconBytes, null, null);
				entity.setLocalFilename(fileid);
				entity.setId(fileid);
				AttachmentVO resultVo = attachmentApplication
						.saveEntity(entity);
				jsonMap.put("icon_id", resultVo.getId());
			}
			jsonMap.put("result", "success");
		}
	} catch (Exception e) {
			log.error("readfile", e);
	}
		log.info("[readfile]" + jsonMap.toString());
		return jsonMap;
	}

	/**
	 * 此方法描述的是：生成114*114图标
	 *
	 * @author: panhm@foreveross.com
	 * @version: 2013-7-26 下午12:46:37
	 */

	@ResponseBody
	@RequestMapping(method = RequestMethod.POST, value = "/icon")
	public Map<String, String> uploadIcon(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, String> result = new HashMap<String, String>();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 获得文件：
		MultipartFile file = multipartRequest.getFile("file");

		try {
			if (file != null) {
				// 保存上传文件信息
				AttachmentVO entity = new AttachmentVO();
				Date date = new Date();
				entity.setAvailable(1);
				entity.setContentType(file.getContentType());
				entity.setCreatedAt(date);
				entity.setModifiedAt(date);
				entity.setUploadFilename(file.getOriginalFilename());
				entity.setSize(file.getSize());
				entity.setUserName(ContextThead.getThreadVar());
				// 生成指定格式大小的图片数据
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				Thumbnails.of(file.getInputStream()).size(114, 114)
						.toOutputStream(out);
				// 将图片保存到云服务
				FileStorageFactory f = FileStorageFactory.getInstance();
				FileStorage fs = f.getFileStorage();

				String id = fs.saveFile(out.toByteArray(), null, null);
				entity.setId(id);
				entity.setLocalFilename(id);
				AttachmentVO resultVo = attachmentApplication
						.saveEntity(entity);
				result.put("result", "success");
				result.put("id", resultVo.getId());
			} else {
				result.put("result", "error");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("[upload]", e);
			result.put("result", "error");
		}
		return result;
	}

	/**
	 * 此方法描述的是：终端上传文件接口
	 *
	 * @author: panhm@foreveross.com
	 * @version: 2013-7-26 下午12:46:37
	 */

	@ResponseBody
	@RequestMapping(method = RequestMethod.POST, value = "/clientUpload")
	public Map<String, String> clientUpload(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, String> result = new HashMap<String, String>();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 获得文件：
		MultipartFile file = multipartRequest.getFile("file");

		try {
			if (file != null) {
				// 保存上传文件信息
				AttachmentVO entity = new AttachmentVO();
				Date date = new Date();
				entity.setAvailable(1);
				entity.setContentType(file.getContentType());
				entity.setCreatedAt(date);
				entity.setModifiedAt(date);
				entity.setUploadFilename(file.getOriginalFilename());
				entity.setSize(file.getSize());
				entity.setUserName(ContextThead.getThreadVar());

				// 将图片保存到云服务
				FileStorageFactory f = FileStorageFactory.getInstance();
				FileStorage fs = f.getFileStorage();
				String id = fs.saveFile(file.getBytes(), null, null);
				entity.setId(id);
				entity.setLocalFilename(id);
				AttachmentVO resultVo = attachmentApplication
						.saveEntity(entity);
				result.put("result", "success");
				result.put("id", resultVo.getId());
			} else {
				result.put("result", "error");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("[upload]", e);
			result.put("result", "error");
		}

		return result;

	}

	/**
	 * 读取模块包的配置文件信息
	 *
	 * @param id
	 * @param response
	 * @param request
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.GET, value = "/{type}/config/{id:.+}")
	public Map<String, Object> readPackFile(@PathVariable String id,
			@PathVariable String type) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("result", "error"); // 默认是返回失败
			// 获取模块包信息
			AttachmentVO entity = attachmentApplication.getEntity(id);

			// 读取云服务模块包，存放到本地指定目录
			FileStorageFactory f = FileStorageFactory.getInstance();
			FileStorage fs = f.getFileStorage();
			String localFileName = entity.getLocalFilename();
			fs.fetchFile(localFileName, null, FileUtils.dirPath
					+ File.separator + localFileName);
			File file = new File(FileUtils.dirPath + File.separator
					+ localFileName);
			if ("zip".equals(type)) {
				// 读取模块zip包里面的配置文件信息
				String stringJson = FileUtils.readZipConfig(file,
						"CubeModule.json");
				if (stringJson != null) {
					JSONObject json = new JSONObject(stringJson.trim());
					log.info("CubeModule.json:" + json.toString());
					jsonMap.put("identifier", json.getString("identifier"));
					jsonMap.put("name", json.getString("name"));
					jsonMap.put("releaseNote", json.getString("releaseNote"));
					jsonMap.put("version", json.getString("version"));
					jsonMap.put("build", json.getString("build"));
					if (!json.isNull("dependencies")) {
						jsonMap.put("dependsOn", json.getString("dependencies"));
					}
					if (!json.isNull("hidden")) {
						jsonMap.put("hidden", json.getString("hidden"));
					}
					if (!json.isNull("icon")) {
						String icon = json.getString("icon");
						byte[] iconBytes = FileUtils.readPngFile(file, icon);
						// 读取logo图片字节,然后生成图片，保存到文件存储表
						entity = new AttachmentVO();
						Date date = new Date();
						entity.setAvailable(1);
						entity.setContentType("images/png");
						entity.setCreatedAt(date);
						entity.setModifiedAt(date);
						entity.setUploadFilename(icon);
						entity.setSize(iconBytes.length);
						String fileid = fs.saveFile(iconBytes, null, null);
						entity.setLocalFilename(fileid);
						entity.setId(fileid);
						AttachmentVO resultVo = attachmentApplication
								.saveEntity(entity);
						jsonMap.put("icon_id", resultVo.getId());
					}
					jsonMap.put("result", "success");
				}
			} else if ("apk".equals(type)) {

			} else if ("ipa".equals(type)) {

			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("readfile", e);

		}
		log.info("[readfile]" + jsonMap.toString());
		return jsonMap;
	}

	/**
	 * 此方法描述的是：文件下载接口
	 *
	 * @author: panhm@foreveross.com
	 * @version: 2013-7-26 下午12:47:29
	 */

	@RequestMapping(method = RequestMethod.GET, value = "/download1/{id}")
	public ResponseEntity<OutputStream> downloadtest(@PathVariable String id) {
		ResponseEntity<OutputStream> res = null;
		try {
			log.info("[attachment]" + id);
			AttachmentVO entity = attachmentApplication.getEntity(id);
			if (entity != null && entity.getId() != null) {
				// 读取云服务文件
				FileStorageFactory f = FileStorageFactory.getInstance();
				FileStorage fs = f.getFileStorage();
				FileInfo fileInfo = fs
						.statFile(entity.getLocalFilename(), null);
				log.info("[data]" + fileInfo.getLength());
				HttpHeaders headers = new HttpHeaders();
				headers.set(
						"Content-Disposition",
						String.format("attachment;   filename=%s",
								entity.getUploadFilename()));
				headers.set("Content-Length", fileInfo.getLength() + "");
				headers.set("Content-Type", entity.getContentType());
				OutputStream outputStream = new ByteArrayOutputStream();
				fs.fetchFile(entity.getLocalFilename(), null, outputStream);
				res = new ResponseEntity<OutputStream>(outputStream, headers,
						HttpStatus.OK);
			} else {
				log.info("[response]" + 400);
				res = new ResponseEntity<OutputStream>(HttpStatus.BAD_REQUEST);
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO Auto-generated catch block
			log.error("[download]", e);
			res = new ResponseEntity<OutputStream>(
					HttpStatus.INTERNAL_SERVER_ERROR);
		}
		return res;
	}
}